package com.intelligentclass.controller;

import com.intelligentclass.entity.Test;
import com.intelligentclass.services.TestService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@RestController
@CrossOrigin(origins="*")
public class ExcelController {

    private static final Logger log = LoggerFactory.getLogger(ExcelController.class);
    private TestService testService;

    @Autowired
    public ExcelController(TestService testService) {
        this.testService = testService;
    }

    @PostMapping("/enterdata")
    public ResponseEntity<?> enterData(@RequestParam String filePath) {
        log.info("Handling enterData request...");

        List<List<String>> data = new ArrayList<>();

        try (FileInputStream fis = new FileInputStream(new File(filePath))) {
            Workbook workbook = new XSSFWorkbook(fis);
            Sheet sheet = workbook.getSheetAt(0);
            Iterator<Row> rowIterator = sheet.iterator();

            while (rowIterator.hasNext()) {
                List<String> rowData = new ArrayList<>();
                Row row = rowIterator.next();
                Iterator<Cell> cellIterator = row.cellIterator();

                Test test = new Test();

                while (cellIterator.hasNext()) {
                    Cell cell = cellIterator.next();
                    switch (cell.getCellType()) {
                        case STRING:
                            rowData.add(cell.getStringCellValue());
                            break;
                        case NUMERIC:
                            rowData.add(String.valueOf(cell.getNumericCellValue()));
                            break;
                        default:
                            rowData.add("");
                            break;
                    }
                }
                test.setC1((int)Float.parseFloat(rowData.get(0)));
                test.setC2((int)Float.parseFloat(rowData.get(1)));
                test.setC3((int)Float.parseFloat(rowData.get(2)));
                testService.save(test);
                data.add(rowData);
            }

            for(var row: data){
                for(var cell: row){
                    System.out.print(cell.toString() + ' ');
                }
                System.out.println();
            }

            return ResponseEntity.ok().body("ok");

        } catch (IOException e) {
            log.error("Error processing Excel file", e);
            return ResponseEntity.status(500).body("err");
        }
    }
}
